﻿using EFCore.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SService;

namespace WMSWeb.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PublicAttachmentController : ControllerBase
    {
        private readonly WmssystemContext myDb;
        private readonly PublicAttachmentS publicAttachmentS;

        public PublicAttachmentController(WmssystemContext myDb, SService.PublicAttachmentS publicAttachmentS)
        {
            this.myDb = myDb;
            this.publicAttachmentS = publicAttachmentS;
        }

        [HttpPost]
        public async Task<IActionResult> Upload(IFormFile file,string num)
        {
            if (file == null || file.Length <= 0)
            {
                return BadRequest("文件不能为空");
            }

            // 判断文件类型
            var isImage = IsImage(file.FileName);

            // 保存文件到服务器
            string folderPath = @"D:\实训内容\实训项目\Wzxm\xms\WMS\src\uploads";
            Directory.CreateDirectory(folderPath);
            var filePath = Path.Combine(folderPath, file.FileName);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            // 保存文件信息到数据库
            var attachment = new PO_PublicAttachment
            {
                Pub_FileName = file.FileName,
                Pub_FilePath = filePath,
                Pub_FileSize = file.Length.ToString(),
                Pub_FileType = isImage ? "图片" : "文件",
                Pub_RelatedID = num,
                Pub_UploadTime = DateTime.Now,
                Pub_CreateTime = DateTime.Now,
                Pub_YeType=1    
            };

            // TODO: 将 attachment 保存到数据库中
          await  publicAttachmentS.FUpd(attachment);

            return Ok("文件上传成功");
        }

        private bool IsImage(string fileName)
        {
            var imageExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif" };
            var extension = Path.GetExtension(fileName);
            return imageExtensions.Contains(extension.ToLower());
        }

    }
}
